<?php
namespace Admin\Controller;
use Think\Controller;
class CommonController extends Controller {

    public function __construct()
    {
        parent::__construct();
        $uid = session('userid');
        if (!$uid){
            $this->error('未登录','/Admin/Base/login',3);
        }
    }


    /**
     * 获取网络文件
     * @param $url
     * @param string $save_dir
     * @param string $filename
     * @param int $type
     * @return array
     */
    public function getImage($url,$save_dir='',$filename='',$type=0){
        if(trim($url)==''){
            return array('file_name'=>'','save_path'=>'','error'=>1);
        }
        if(trim($save_dir)==''){
            $save_dir='./';
        }
//        if(trim($filename)==''){//保存文件名
//            $ext=strrchr($url,'.');
//            if($ext!='.gif'&&$ext!='.jpg'){
//                return array('file_name'=>'','save_path'=>'','error'=>3);
//            }
//            $filename=time().$ext;
//        }
        if(0!==strrpos($save_dir,'/')){
            $save_dir.='/';
        }
        //创建保存目录
        if(!file_exists($save_dir)&&!mkdir($save_dir,0777,true)){
            return array('file_name'=>'','save_path'=>'','error'=>5);
        }
        //获取远程文件所采用的方法
        if($type){
            $ch=curl_init();
            $timeout=5;
            curl_setopt($ch,CURLOPT_URL,$url);
            curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
            curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
            $img=curl_exec($ch);
            curl_close($ch);
        }else{
            ob_start();
            readfile($url);
            $img=ob_get_contents();
            ob_end_clean();
        }
        //$size=strlen($img);
        //文件大小
        $fp2=@fopen($save_dir.$filename,'a');
        fwrite($fp2,$img);
        fclose($fp2);
        unset($img,$url);
        return array('file_name'=>$filename,'save_path'=>$save_dir.$filename,'error'=>0);
    }



    /**
     * post请求
     * @param $url
     * @param $postdata
     * @return mixed
     */
    public function getcomponent($url,$postdata){

        $ch = curl_init(); //用curl发送数据给api

        curl_setopt( $ch, CURLOPT_POST, true );
        curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
        curl_setopt( $ch, CURLOPT_URL, $url );
        curl_setopt( $ch, CURLOPT_POSTFIELDS, $postdata );
        curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, FALSE );
        curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, FALSE );
        $response = curl_exec($ch);
        curl_close( $ch );
        $rest = json_decode($response,true);
        return $rest;
    }

    /**
     * get请求
     * @param $url
     * @return mixed
     */
    public function curlget($url){
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, FALSE );
        curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, FALSE );
        $response = curl_exec($ch);
        curl_close( $ch );
        $rest = json_decode($response,true);
        return $rest;
    }

    /**
     * 更新token
     * @param $appid
     * @param $secret
     * @return mixed
     */
    public function updatetoken($appid,$secret){


        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$secret";
        $res = $this->curlget($url);

        $where['appid'] = $appid;
        $where['secret'] = $secret;
        $token =  M('access_token')->field('access_token')->where($where)->find();

        $data = array(
            'access_token'=>$res['access_token'],
            'expires_in'=>$res['expires_in'],
            'createtime'=>time(),
            'appid'=>$appid,
            'secret'=>$secret,
        );
        if ($token){
            M('access_token')->where($where)->save($data);
        }else{
            if ($res['access_token']){
                M('access_token')->data($data)->add();
            }
        }

        return $res['access_token'];

    }

    /**
     * 获取token
     * @param $appid
     * @param $secret
     * @return mixed
     */

    public function gettoken($appid,$secret){

        $name = $appid.'access_token';
        $access_token = S($name);

        if (!empty($access_token)){
            return $access_token;
        }

        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$secret";
        $res = $this->curlget($url);

        S($name,$res['access_token'],$res['expires_in']);

        return S($name);

    }

    /**
     * 发送模板消息
     */
    public function sendtemplate($appid,$secret,$data){

        $access_token = $this->gettoken($appid,$secret);
        $url = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=$access_token";

        $res = $this->getcomponent($url,json_encode($data,true));

        return $res;

    }

    /**
     * redis 缓存的access_token
     * @param $appid
     * @param $secret
     * @param null $redis
     * @return mixed
     */
    public function redis_access_token($appid,$secret, $redis = NULL)
    {
        if (empty($redis))
        {
            $redis = new \Redis();
            $redis->connect('127.0.0.1',6379);
        }

        $token   =   $redis->get('access_token_'.$appid);
        if (empty($token))
        {
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$secret";
            $res = $this->curlget($url);

            $data = array(
                'access_token'=>$res['access_token'],
                'expires_in'=>$res['expires_in'],
                'createtime'=>time(),
                'appid'=>$appid,
                'secret'=>$secret,
            );

            $data_json  =   json_encode($data);
            $redis->set('access_token_'.$appid, $data_json);
            return $res['access_token'];
        }
        else
        {
            $token   =   json_decode($token,true);

            $access_token = $token['access_token'];
            if (time()-$token['access_token']>=$token['expires_in'])
            {
                $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$secret";
                $res = $this->curlget($url);

                $data = array(
                    'access_token'=>$res['access_token'],
                    'expires_in'=>$res['expires_in'],
                    'createtime'=>time(),
                    'appid'=>$appid,
                    'secret'=>$secret,
                );

                $data_json      =   json_encode($data);
                $redis->set('access_token_'.$appid, $data_json);
                $access_token   =   $res['access_token'];
            }
            return $access_token;
        }
    }
}